//
//  CYAddressBookVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/21.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYAddressBookVController.h"
#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>
#import "AddressBook.h"
#import "PinYin4Objc.h"
#import "CYPerson.h"
#import "CYSearchTVController.h"
#import "CYABDetailVController.h"
#import "CYNavigationVController.h"
#import "CYABTool.h"
#import "CYEscape.h"
#import "UIImageView+WebCache.h"
#import "CYCreditDetailTVController.h"
#import "CYDefaultRecordAO.h"
#import "DSNavigationBar.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "CYAddressBookCell.h"
#import "CYTabBarVController.h"
#import "PinYin5Objc.h"
#import <objc/runtime.h>
#import "CYYSTricksterVC.h"
#import "CYAddressBookTool.h"
#import "CYABDetailVC.h"
#import "CYABDetailTableVC.h"
#import "CYABDetailPageVC.h"
#import "RegexKitLite.h"
#import "CYMeHttpTool.h"
#import "CYYSDetailVC.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "JPUSHService.h"
#import "CYLoginHttpTool.h"
#import "UIAlertView+Block.h"

@interface CYAddressBookVController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, CYAddressBookCellDelegate, CYTabBarVControllerDelegate, CYSearchTVDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) RHAddressBook *addressBook;

@property (nonatomic, strong) NSMutableArray *allPeople;
@property (nonatomic, strong) NSMutableArray *peopleSections;
@property (nonatomic, strong) NSMutableArray *pinYinHead;
@property (nonatomic, strong) NSMutableArray *chineseSort;
@property (nonatomic, strong) NSMutableArray *cyPersonSections;//显示数组
@property (nonatomic, strong) NSArray *names;//所有人的名字
@property (nonatomic, copy) NSString *searchText;
@property (nonatomic, weak) CYSearchTVController *searchTVController;

@property (nonatomic, strong) NSMutableArray *localAddressBooks;//本地联系人数组
@property (nonatomic, strong) NSMutableArray *tricksters;//失信联系人数组
@property (nonatomic, strong) NSArray *ysTricksters;//疑似失信人

@property (nonatomic, weak) UILabel *hintLabel;//无数据提示字
@property (nonatomic, assign) NSInteger selectedSegIndex;//选中的导航条

@property (nonatomic, strong) NSString *ysHint;
@property (nonatomic, strong) NSString *sxHint;

@property (nonatomic, assign) BOOL sxLoadState;
@property (nonatomic, assign) BOOL ysLoadState;

@property (nonatomic, weak) CYYSTricksterVC *ysTricksterVC;//疑似失信人controller

@property (nonatomic, weak) UIButton *reloadYSBtn;
@property (nonatomic, weak) UIButton *reloadSXBtn;

@property (weak, nonatomic) IBOutlet UISearchBar *abSearchBar;
@property (weak, nonatomic) IBOutlet UITableView *abTableView;
@property (weak, nonatomic) IBOutlet UIButton *cover;
@property (weak, nonatomic) IBOutlet UIView *naviView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableRightConstraint;
@property (weak, nonatomic) IBOutlet UIImageView *tipView;//无老赖提示view

//更新信息
@property (nonatomic, strong) NSString *updatedetail; //更新内容
@property (nonatomic, strong) NSString *versionNo; //版本号
@property (nonatomic, strong) NSString *url; //下载链接


@end

@implementation CYAddressBookVController

- (RHAddressBook *)addressBook {
    if (!_addressBook) {
        _addressBook = [[RHAddressBook alloc] init];
    }
    return _addressBook;
}

- (NSMutableArray *)localAddressBooks {
    if (_localAddressBooks == nil) {
        _localAddressBooks = [NSMutableArray array];
    }
    return _localAddressBooks;
}

- (NSMutableArray *)tricksters {
    if (_tricksters == nil) {
        _tricksters = [NSMutableArray array];
    }
    return _tricksters;
}

- (NSMutableArray *)allPeople {
    if (_allPeople == nil) {
        _allPeople = [NSMutableArray array];
    }
    return _allPeople;
}

- (NSMutableArray *)peopleSections {
    if (_peopleSections == nil) {
        _peopleSections = [NSMutableArray array];
    }
    return _peopleSections;
}

- (NSMutableArray *)pinYinHead {
    if (_pinYinHead == nil) {
        _pinYinHead = [NSMutableArray array];
    }
    return _pinYinHead;
}

- (NSMutableArray *)chineseSort {
    if (_chineseSort == nil) {
        _chineseSort = [NSMutableArray array];
    }
    return _chineseSort;
}

- (NSMutableArray *)cyPersonSections {
    if (_cyPersonSections == nil) {
        _cyPersonSections = [NSMutableArray array];
    }
    return _cyPersonSections;
}

- (CYSearchTVController *)searchTVController {
    if (!_searchTVController) {
        CYSearchTVController *search = [[CYSearchTVController alloc] init];
        search.delegate = self;
        [self addChildViewController:search];
        _searchTVController = search;
        
        [self.view addSubview:search.view];
        [search didMoveToParentViewController:self];
        [_searchTVController.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
        [_searchTVController.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.abSearchBar];
    }
    return _searchTVController;
}

- (void)setSearchText:(NSString *)searchText {
    _searchText = [searchText copy];
    
    searchText = searchText.uppercaseString;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person.name contains %@ or pinyin contains %@ or pinyinHeaderFirst contains %@ or pinyinHeader contains %@", searchText, searchText, searchText, searchText];
    NSMutableArray *result = [NSMutableArray array];
    for (NSArray *persons in self.cyPersonSections) {
        for (CYPerson *person in persons) {
            [result addObject:person];
        }
    }
    self.searchTVController.persons = [result filteredArrayUsingPredicate:predicate];
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [JPUSHService setBadge:0];
    //            _pointImagView.hidden = YES;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [super viewDidLoad];
    @try {
        [self setExtraCellLineHidden];
        [self requestAccessAddressBook];
        [self setupBaseProperty];
        [self accessAllPeople];
        //person排序
        [self sortPerson];
        //设置添加联系人按钮
        [self setupAddBtn];
        //匹配失信联系人
        [self loadTricksters];
        //匹配疑似失信人
        //    [self loadYsTricksters];
        [self setupYSTrickster];
        //设置无数据提示view
        [self setupHintView];
        [self setupNavigationView];
        //设置监听
        [self setupNotification];
         
    }
    @catch (NSException *exception) {
        [self reportException:exception reason:@"通讯录初始化错误"];
        NSAssert(NO, @"通讯录初始化错误");
    }
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];      //获取项目版本号
    [CYHttpTool postWithURL:[CYURL shared].updateVersion params:@{@"versionNo":version,@"type":@"2"} success:^(id json) {
         
        CYLog(@"%@",[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        
        NSString *str = jsonInfo.success;
        CYLog(@"str = %@",str);
        if ([str isEqualToString:@"update"]) {
            NSDictionary *data = jsonInfo.data;
             NSString *status = [data objectForKey:@"status"];
             _updatedetail =[data objectForKey:@"content"];
             _versionNo = [data objectForKey:@"versionNo"];
             _url = [data objectForKey:@"url"];

             if (status && status.intValue == 1) {
                  //强制更新
                  [self checkAppUpdate];
             }else{
                  //不强制更新
                  UIAlertView *uploadAlert = [[UIAlertView alloc]initWithTitle:@"您有新的更新" message:_updatedetail delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                  [uploadAlert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
                       if (buttonIndex == 1) {
                            // 此处加入应用在app store的地址，方便用户去更新，一种实现方式如下：
                            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",_url]];
                            //测试
                            //    NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://dn-ipaplist.qbox.me/CreditAddressBook_2.9.3.plist"];
                            
                            CYLog(@"url=%@",url);
                            //打开下载链接
                            [[UIApplication sharedApplication] openURL:url];
                            
                       }
                       
                  }];
                  
             }
             
            CYLog(@"detail = %@,version= %@, url = %@",_updatedetail,_versionNo,_url);
        }else{
            //不做任何操作，项目版本号=服务器控制版本号。
             CYLog(@"没有新的更新");
        }
        
        
    } failure:^(NSError *error) {
        
    }];
}





-(void)checkAppUpdate
{
    
    UIWindow *widow =  [UIApplication sharedApplication].keyWindow;
    UIView *zhezhaoView = [[UIView alloc]init];
    zhezhaoView.frame = CGRectMake(0, 0, [[ UIScreen mainScreen ] bounds].size.width, [[ UIScreen mainScreen ] bounds].size.height);
    zhezhaoView.backgroundColor = [UIColor clearColor];
    [widow addSubview:zhezhaoView];
    UIView *uploadView = [[UIView alloc]init];
    uploadView.backgroundColor = [UIColor whiteColor];
//    uploadView.frame = CGRectMake(self.view.width/8, self.view.height/6, self.view.width-self.view.width/4, self.view.height - self.view.height/2);
    uploadView.bounds = CGRectMake(0,0,self.view.width-self.view.width/4, self.view.height-self.view.height/2);
    uploadView.center = self.view.center;
    uploadView.layer.borderWidth = 1;
    uploadView.layer.cornerRadius = 8;
    uploadView.layer.borderColor = CYColor(174, 174, 174, 1).CGColor;
    [zhezhaoView addSubview:uploadView];
    
    UILabel *titleLab  = [[UILabel alloc]init];
    titleLab.text = [NSString stringWithFormat:@"您有新的更新"];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.frame = CGRectMake(0, 5,uploadView.width, uploadView.height/8);
    
    
    UIView *lineView1 = [[UIView alloc]init];
    lineView1.frame = CGRectMake(4, titleLab.y+titleLab.height+5, titleLab.width-8, 1);
    lineView1.backgroundColor = CYColor(174, 174, 174, 1);
    
//    UILabel *detailLab = [[UILabel alloc]init];
//    detailLab.text = _updatedetail;
//    detailLab.numberOfLines = 10;
//    detailLab.frame = CGRectMake(4, lineView1.y+5, titleLab.width-8, uploadView.height/1.4);
//    detailLab.backgroundColor = [UIColor clearColor];

    UITextView *textview = [[UITextView alloc]init];
    textview.frame =CGRectMake(4, lineView1.y+5, titleLab.width-8, uploadView.height/1.4);
     textview.editable = NO;
    textview.font = [UIFont systemFontOfSize:16];
    textview.text = _updatedetail;
    textview.textColor = [UIColor grayColor];
    
    UIView *lineView2 = [[UIView alloc]init];
    lineView2.frame = CGRectMake(4, textview.y+textview.height+2, uploadView.width-8, 1);
    lineView2.backgroundColor = CYColor(174, 174, 174, 1);
    
    UIButton *uploadBtn = [[UIButton alloc]init];
    uploadBtn.frame = CGRectMake(titleLab.x, lineView2.y+4, uploadView.width, 30);
    [uploadBtn addTarget:self action:@selector(uploadclick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *noticeLab = [[UILabel alloc]init];
    noticeLab.frame = uploadBtn.frame;
    noticeLab.text  = @"更新";
    noticeLab.textColor = CYColor(120, 219, 113, 1);
    noticeLab.textAlignment = NSTextAlignmentCenter;
    
    [uploadView addSubview:titleLab];
    [uploadView addSubview:lineView1];
    [uploadView addSubview:textview];
    [uploadView addSubview:lineView2];
    [uploadView addSubview:uploadBtn];
    [uploadView addSubview:noticeLab];
}

-(void)uploadclick{
     // itms-services://协议为苹果给企业应用安装使用的协议
     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",_url]];
     //测试
     //    NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://dn-ipaplist.qbox.me/CreditAddressBook_2.9.3.plist"];
     
     [[UIApplication sharedApplication] openURL:url];
    
}

-(void)checkuuid{
    CYAlertView(@"check!");
    
}

- (void)setupBaseProperty {
    if (IOS8) {
        self.tableRightConstraint.constant = -16.f;
    }
    
    CYTabBarVController *tabBar = (CYTabBarVController *)self.tabBarController;
    tabBar.tabBarDelegate = self;
    
    [self.abSearchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_search"]];
    self.abTableView.sectionIndexColor = [UIColor grayColor];
    self.abTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.abTableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
    self.view.backgroundColor = [UIColor whiteColor];
    self.hintLabel.hidden = YES;
    self.tipView.hidden = YES;
}

- (void)setupAddBtn {
    //设置添加按钮
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, 0, 40, 20);
    addBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    addBtn.backgroundColor = [UIColor clearColor];
    
    [addBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
    self.navigationItem.leftBarButtonItem = left;
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
}

#pragma mark - 添加新联系人
//添加按钮方法
- (void)buttonAction:(UIButton *)sender {
    [CYAddressBookTool newPersonWithController:self person:nil completion:^(id obj) {
        [self reloadAbtableViewDataSource];
        [self.abTableView reloadData];
    }];
}

#pragma mark - 读取通讯录授权
/**
 *  读取通讯录授权
 */
- (void)requestAccessAddressBook {
    RHAddressBook *book = self.addressBook;
    if ([RHAddressBook authorizationStatus] == RHAuthorizationStatusNotDetermined){
        //request authorization
        [book requestAuthorizationWithCompletion:^(bool granted, NSError *error) {
            [self accessAllPeople];
            [self sortPerson];
            //匹配失信联系人
            [self loadTricksters];
            //匹配疑似失信人
//            [self loadYsTricksters];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.abTableView reloadData];
            });
            
//             [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(addressBookChanged:) name:RHAddressBookExternalChangeNotification object:nil];
            
        }];
    }
}

/**
 *  读取通讯录数据
 */
- (void)accessAllPeople {
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    
    NSArray *allPeople = [CYABTool accessAllPeople];
    
    [self.allPeople removeAllObjects];
    [self.allPeople addObjectsFromArray:allPeople];
}

/**
 *  刷新通讯录数据
 */
- (void)reloadAllPeople {
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    
    NSArray *allPeople = [CYABTool reloadAllPeople];
    
    [self.allPeople removeAllObjects];
    [self.allPeople addObjectsFromArray:allPeople];
}

//重新加载与处理数据源
- (void)reloadAbtableViewDataSource {
    //从新读取手机中的通讯录
    [self reloadAllPeople];
    [self sortPerson];
    //匹配失信联系人
    [self loadTricksters];
    //匹配疑似失信人
    //        [self loadYsTricksters];
}

#pragma mark - 读取通讯录排序
/**
 *  处理通讯录数据的拼音并分组
 */
/**- (void)toPinYinHead {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    //1获取姓名的数组
    NSMutableArray *names = [NSMutableArray array];
    for (RHPerson *person in self.allPeople) {
        [names addObject:person.name];
    }
    self.names = names;
    
    //2获取首字母并排序
    NSArray *pinyinHead = [PinYinForObjc pinYinHeadBySort:names];
    [self.pinYinHead addObjectsFromArray:pinyinHead];
    
    //3汉字排序, 返回二维数组
    NSArray *chineseScort = [PinYinForObjc chineseSort:names];
    
    //4对RHPersonsp排序
    NSArray *personSort = [self.allPeople sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        RHPerson *p1 = obj1;
        RHPerson *p2 = obj2;
        NSString *p1name = [[PinYinForObjc chineseConvertToPinYin:p1.name] uppercaseString];
        NSString *p2name = [[PinYinForObjc chineseConvertToPinYin:p2.name] uppercaseString];
        return [p1name compare:p2name];
    }];
    
    //5根据汉字分组排序对RHPersons进行分组排序
    NSMutableArray *personSections = [NSMutableArray array];
    int indexOfArr = 0;//personSort数组的下标
    for (int i = 0; i < chineseScort.count; i++) {
        NSMutableArray *persons = [NSMutableArray array];
        NSArray *chinese = chineseScort[i];
        for (int j = indexOfArr; j < chinese.count + indexOfArr; j++) {
            [persons addObject:personSort[j]];
        }
        indexOfArr += chinese.count;//personSort数组的下标
        [personSections addObject:persons];
    }
    
    [self.chineseSort addObjectsFromArray:personSections];
    
    
    //7.对CYPerson进行分组存储
    NSMutableArray *cyPersonSectionss = [NSMutableArray array];
    for (int i = 0; i < personSections.count; i++) {
        NSArray *rhPersons = personSections[i];
        NSMutableArray *cyPersons = [NSMutableArray array];
        for (RHPerson *rhPerson in rhPersons) {
            
            CYPerson *cyPerson = [CYABTool cyPersonFromRHPerson:rhPerson];
            [cyPersons addObject:cyPerson];
        }
        [cyPersonSectionss addObject:cyPersons];
    }
    [self.cyPersonSections addObjectsFromArray:cyPersonSectionss];
    [self.localAddressBooks addObjectsFromArray:self.cyPersonSections];//本地联系人保存
}*/

/**
 *  通讯录排序
 */
- (void)sortPerson {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    
    //获取姓名的数组
    NSMutableArray *names = [NSMutableArray array];
    for (RHPerson *person in self.allPeople) {
        if (person.name) {
            [names addObject:person.name];
        }
    }
    self.names = names;
    
    //为CYPerson设置RHPerson
    NSMutableArray *allPerson = [NSMutableArray array];
    [allPerson addObjectsFromArray:[CYABTool cyPersonsFromRHPersons:self.allPeople]];
    
    //通讯录排序
    NSArray *sortWithNameArr = [allPerson sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CYPerson *p1 = obj1;
        CYPerson *p2 = obj2;
        return [p1.pinyin compare:p2.pinyin];
    }];
    
    //去除重复首字母并排序
    NSArray *pinyinHeadersArr = [sortWithNameArr valueForKeyPath:@"pinyinHeaderFirst"];
    NSSet *pinyinHeadersSet = [NSSet setWithArray:pinyinHeadersArr];
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];
    NSArray *sortSetArray = [pinyinHeadersSet sortedArrayUsingDescriptors:sortDesc];
    
    //根据首字母分组
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *head in sortSetArray) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pinyinHeaderFirst == %@", head];
        NSArray *filterAfrr = [sortWithNameArr filteredArrayUsingPredicate:predicate];
        [arr addObject:[NSMutableArray arrayWithArray:filterAfrr]];
    }
    
    //缓存本地通讯录
    [self.localAddressBooks removeAllObjects];
    [self.localAddressBooks addObjectsFromArray:arr];
    //设置显示数据
    [self.cyPersonSections removeAllObjects];
    [self.cyPersonSections addObjectsFromArray:arr];
}

#pragma mark - 失信人，疑似失信人匹配
/**
 *  匹配失信联系人
 */
- (void)loadTricksters {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    self.sxLoadState = NO;
    NSArray *phones = [self phonesFromArr];
    phones = [CYABTool formatPhoneNumbers:phones];
    //拼接电话号码
    NSString *phonesStr = [self stringByPhones:phones];
    //加载网络数据
    NSDictionary *params = @{@"phones": phonesStr};
    [CYABTool defaultRecordsWithParams:params success:^(NSArray *cyPersons) {
        
        NSMutableArray *simpleRecordsDic = [NSMutableArray array];//保存到本地数组
        //为服务器返回的数据与本地进行匹配
        for (CYPerson *cyperson in [cyPersons lastObject]) {
            NSString *phone = cyperson.simpleRecord.phone;
            
            if (!phone || [phone isEqualToString:@""]) continue;
            
            for (RHPerson *rhPerson in self.allPeople) {
                NSArray *rhphones = [CYABTool formatPhoneNumbers:rhPerson.phoneNumbers.values];
                
                NSPredicate *predic = [NSPredicate predicateWithFormat:@"SELF contains %@", phone];
                NSArray *phoneArr = [rhphones filteredArrayUsingPredicate:predic];
                
                if (phoneArr.count) {
                    cyperson.person = rhPerson;
                    
                    CYSimpleRecord *simpRec = cyperson.simpleRecord;
                    simpRec.name = rhPerson.name;
                    [simpleRecordsDic addObject:simpRec.keyValues];
                    continue;
                }
            }
        }
        //失信人本地数据缓存
        [self.tricksters removeAllObjects];
        [self.tricksters addObjectsFromArray:cyPersons];
        
        //保存到本地以便个人中心读取
        NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
        [defs setObject:simpleRecordsDic forKey:CYSimpleRecordsDicKey];
        [defs synchronize];
        
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //标识右边图标
            [self updateIconStyleSXWithArray:cyPersons.lastObject];
            if (self.selectedSegIndex == CYIndexFirst) {
                [self.abTableView reloadData];
            }
//        });
        
        self.sxLoadState = YES;
        [MBProgressHUD hideHUDForView:self.abTableView animated:NO];
    } failure:^(NSError *error) {
        CYLog(@"匹配失信联系人服务器链接错误：%@", error);
        self.sxLoadState = YES;
        if (error.code == CYErrorCodeNOData) {
            self.sxHint = @"没有更多数据";
            self.reloadSXBtn.hidden = YES;
            self.reloadYSBtn.hidden = YES;
        } else {
            self.sxHint = @"网络出错";
            self.reloadSXBtn.hidden = NO;
            self.reloadYSBtn.hidden = YES;
        }
        if (self.selectedSegIndex == CYIndexSecond) {
            [MBProgressHUD hideHUDForView:self.abTableView animated:NO];
//            self.hintLabel.hidden = NO;
            self.tipView.hidden = NO;
            self.hintLabel.text = self.sxHint;
        } else {
            self.reloadSXBtn.hidden = YES;
            self.reloadYSBtn.hidden = YES;
            self.hintLabel.hidden = YES;
            self.tipView.hidden = YES;
        }
    }];
}

/**
 *  匹配疑似失信联系人
 */
- (void)loadYsTricksters {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *name in self.names) {
        NSDictionary *nameDic = @{@"name": name};
        [arr addObject:nameDic];
    }

    NSString *json = [NSString jsonStringWithArray:arr];
    [CYABTool ysDefaultPersonsWithParams:@{@"data": json} success:^(NSArray *defrs) {
        for (CYPerson *person in defrs) {
            for (RHPerson *rhperson in self.allPeople) {
                if ([person.name isEqualToString:rhperson.name]) {
                    person.person = rhperson;
                    continue;
                }
            }
        }
        self.ysTricksters = @[defrs];
        
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //标识cell右边图标
            [self updateIconStyleYSWithArray:defrs];
            if (self.selectedSegIndex == CYIndexFirst || self.selectedSegIndex == CYIndexThird) {
                [self.abTableView reloadData];
            }
//        });
        
        self.ysLoadState = YES;
        [MBProgressHUD hideHUDForView:self.abTableView];
    } failure:^(NSError *error) {
        self.ysLoadState = YES;
        if (error.code == CYErrorCodeParamsError) {
            self.ysHint = @"没有更多数据";
        } else {
            self.ysHint = @"网络出错";
        }
        if (self.selectedSegIndex == CYIndexThird) {
            [MBProgressHUD hideHUDForView:self.abTableView];
//            self.hintLabel.hidden = NO;
            self.tipView.hidden = NO;
            self.hintLabel.text = self.ysHint;
            self.reloadYSBtn.hidden = NO;
        }
    }];
}

- (void)setupYSTrickster {
    CYYSTricksterVC *ys = [[CYYSTricksterVC alloc] init];
    ys.names = self.names;
    ys.navi = self.navigationController;
    //    CGFloat tabY = self.abTableView.frame.origin.y - 38;
    ys.view.frame = CGRectMake(0, 64 +55, CYScreeSize.width, CYScreeSize.height - 64 - 46);
    [self addChildViewController:ys];
    [ys didMoveToParentViewController:self];
    self.ysTricksterVC = ys;
}

/**
 *  从数组中获取每个成员的电话号码
 */
- (NSArray *)phonesFromArr {
    NSArray *rhPersons = [self.localAddressBooks valueForKeyPath:@"person"];
    
    NSMutableArray *phones = [NSMutableArray array];
    for (NSArray *rhpersons in rhPersons) {
        for (RHPerson *rhPerson in rhpersons) {
            if (rhPerson.phoneNumbers.values.count) {
                [phones addObjectsFromArray:rhPerson.phoneNumbers.values];
            }
        }
    }
    return phones;
}

/**
 *  电话号码数组拼接成字符串
 */
- (NSString *)stringByPhones:(NSArray *)strs {
    NSMutableString *phonesStr = [NSMutableString string];
    for (int i = 0; i < strs.count; i++) {
        [phonesStr appendFormat:@"%@,", strs[i]];
    }
    NSString *str = [phonesStr substringToIndex:phonesStr.length - 1];
    return str;
}

/**
 *  页面显示时检查通讯录读取权限
 */
-(void)viewDidAppear:(BOOL)animated {
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) {
        [[[UIAlertView alloc] initWithTitle:nil message:CYFailureCue delegate:nil cancelButtonTitle:CYToolTips otherButtonTitles:nil] show];
    }
    [super viewDidAppear:animated];
}

/**
 *  根据失信人更新cell的iconBtn图标及点击事件
 */
- (void)updateIconStyleSXWithArray:(NSArray *)arr {
    if (!arr.count) return;
    for (NSArray *cypersons in self.localAddressBooks) {
        for (CYPerson *cyperson in cypersons) {
            for (CYPerson *arrperson in arr) {
                if (CYStringEqualTo(arrperson.phone, cyperson.phone)) {
                    cyperson.iconType = CYIconTypeSX;
                    cyperson.show = YES;
                    cyperson.simpleRecord = arrperson.simpleRecord;
                    continue;
                }
            }
        }
    }
}

/**
 *  根据疑似失信人更新cell的iconBtn图标及点击事件
 */
- (void)updateIconStyleYSWithArray:(NSArray *)arr {
    if (!arr.count) return;
    for (NSArray *cypersons in self.localAddressBooks) {
        for (CYPerson *cyperson in cypersons) {
            for (CYPerson *arrperson in arr) {
                if (CYStringEqualTo(arrperson.name, cyperson.name) && cyperson.iconType != CYIconTypeSX) {
                    cyperson.iconType = CYIconTypeYS;
                    cyperson.show = YES;
                    continue;
                }
            }
        }
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.cyPersonSections.count) {
        return self.cyPersonSections.count;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sections = self.cyPersonSections[section];
    if (sections.count) {
        return sections.count;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //添加显示view
    UIView *view = [[UIView alloc] initForAutoLayout];
    view.backgroundColor = self.view.backgroundColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, self.view.width, 15)];
    [view addSubview:label];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor grayColor];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 15, self.view.width, 1)];
    [view addSubview:line];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    //设置标题
    NSArray *personSection = self.cyPersonSections[section];
        CYPerson *person = nil;
        if (personSection.count) {
            person = [personSection firstObject];
            if (person.segmentTag == 1 || person.segmentTag == 2) {
                NSArray *arr = self.cyPersonSections[section];
                label.text = [NSString stringWithFormat:@"共%lu人", (unsigned long)arr.count];
            } else {
                label.text = person.pinyinHeaderFirst;
            }
        }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *persons = self.cyPersonSections[indexPath.section];
    CYPerson *cyperson = persons[indexPath.row];
    
        CYAddressBookCell *cell = [CYAddressBookCell cellWithTableView:tableView];
    
        cell.person = cyperson;
        cell.cellDelegate = self;
        [cell iconBtnAddTarget:self action:@selector(iconBtnClick:)];
        
        return cell;
//    }
    
    
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.selectedSegIndex == CYIndexFirst) {
        return YES;
    }
    return NO;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return @"删除";
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

        NSMutableArray *arr = self.localAddressBooks[indexPath.section];
        
        CYPerson *person = arr[indexPath.row];
        RHPerson *rhperson = person.person;

        ABRecordRef a = rhperson.recordRef;
    
        [self removePersonWithRecord:a];//从通讯录里删除
    
        [arr removeObjectAtIndex:indexPath.row];
    
//        [self.addressBook removePerson:rhperson error:nil];
    
        [self.abTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];  //删除对应数据的cell

}

/**
 *  删除指定的记录
 *
 *  @param recordRef 要删除的记录
 */
-(void)removePersonWithRecord:(ABRecordRef)recordRef{
    ABAddressBookRemoveRecord([self.addressBook addressBookRef], recordRef, NULL);//删除
    ABAddressBookSave([self.addressBook addressBookRef], NULL);//删除之后提交更改
}


/**
 *  设置tableview右边导航条
 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *pinyinHeaders = [NSMutableArray array];
    for (NSArray *persons in self.cyPersonSections) {
        if (persons.count) {
            CYPerson *person = [persons firstObject];
            if (person.segmentTag == 0) {
                [pinyinHeaders addObject:person.pinyinHeaderFirst];
            }
        }
    }
    return pinyinHeaders;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //设置点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *persons = self.cyPersonSections[indexPath.section];
    CYPerson *cyperson = persons[indexPath.row];
    
    if (cyperson.segmentTag == 2) {
        CYYSDetailVC *YSDetail = [[CYYSDetailVC alloc] init];
        YSDetail.person = cyperson;
        YSDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:YSDetail animated:YES];
    } else {
//        CYABDetailTableVC *controll = [CYABDetailTableVC le_loadFromStoryBoard:self.storyboard];
        
//        CYABDetailVController *controll = [[CYABDetailVController alloc] init];
        cyperson.pushTag = 1;
//        controll.person = cyperson;
        
//        CYABDetailVC *controll = [CYABDetailVC le_loadFromStoryBoard:self.storyboard];
        
        
        cyperson.pushTag = 1;
//        controll.person = cyperson;
        
        CYABDetailPageVC *controll = [[CYABDetailPageVC alloc] initWithPerson:cyperson andCallRecord:nil defrId:cyperson.simpleRecord.recordId];
        
        controll.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controll animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.f;
}

#pragma mark - scrollDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view.window endEditing:YES];//关闭键盘
}

#pragma mark - SearchBarDelegate
/**
 *  输入文字时搜索
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length) {
        self.searchText = searchText;
        self.searchTVController.view.hidden = NO;
    }else {
        self.searchTVController.view.hidden = YES;
    }
}

/**
 *  键盘弹出:搜索框开始编辑文字
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    //隐藏导航栏
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIView animateWithDuration:.3 animations:^{
        self.naviView.transform = CGAffineTransformMakeTranslation(0, -self.naviView.frame.size.height - 20);
    }];
    //设置输入框背景图片
    [searchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_search_high"]];
    //显示搜索框取消按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    //显示遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.4;
    }];
}

/**
 *  键盘退下:搜索框结束编辑文字
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    //显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [UIView animateWithDuration:.3 animations:^{
        self.naviView.transform = CGAffineTransformIdentity;
    }];
    //设置输入框背景图片
    [searchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield"]];
    //隐藏搜索框取消按钮
    [searchBar setShowsCancelButton:NO animated:YES];
    //隐藏遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.0;
    }];
    //移除搜索结果
    self.searchTVController.view.hidden = YES;
    searchBar.text = nil;
}

/**
 *  点击搜索框取消按钮时键盘退下，遮盖消失
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

/**
 *  点击遮盖退下键盘
 */
- (IBAction)coverClick:(id)sender {
    [self.abSearchBar resignFirstResponder];//设置不做第一响应者
}

#pragma mark - 导航条点击
- (IBAction)segmentClick:(id)sender {
    [MBProgressHUD hideHUDForView:self.abTableView animated:NO];
    
    UISegmentedControl *s = sender;
    self.selectedSegIndex = s.selectedSegmentIndex;
    if (s.selectedSegmentIndex == CYIndexSecond) {//失信人
        [self.ysTricksterVC.view removeFromSuperview];
        //清空显示数组
        [self.cyPersonSections removeAllObjects];
        //隐藏搜素框以及失信匹配的联系人
        self.abSearchBar.alpha = 0;
        self.abTableView.transform = CGAffineTransformMakeTranslation(0, -self.abSearchBar.frame.size.height - 2);
        self.reloadYSBtn.hidden = YES;
        
         
        //失信匹配人为空时显示无数据提示文字
        if (!self.tricksters.count) {
              CYAlertView(@"暂无数据");
             if (self.sxLoadState) {
                  
//                self.hintLabel.hidden = NO;
                self.tipView.hidden = NO;
                self.hintLabel.text = self.sxHint;
                if (CYStringEqualTo(self.sxHint, @"网络出错")) {
                    self.reloadSXBtn.hidden = NO;
                    self.reloadYSBtn.hidden = YES;
                } else {
                    self.reloadYSBtn.hidden = YES;
                    self.reloadSXBtn.hidden = YES;
                }
            } else {
                 

            }
        } else {
            self.hintLabel.hidden = YES;
            self.tipView.hidden = YES;
            self.reloadSXBtn.hidden = YES;
            self.reloadYSBtn.hidden = YES;
            [MBProgressHUD hideHUDForView:self.abTableView animated:NO];
            
            //清空显示数组，加载失信匹配的联系人数组
            [self.cyPersonSections addObjectsFromArray:self.tricksters];
        }
        [self.abTableView reloadData];
    }else if (s.selectedSegmentIndex == CYIndexFirst) {//通讯录
         
        [self.ysTricksterVC.view removeFromSuperview];
        
//        self.abSearchBar.hidden = NO;
//        self.abTableView.transform = CGAffineTransformIdentity;
        //显示搜索框以及通讯录本地数据
        [UIView animateWithDuration:.3 animations:^{
            self.abSearchBar.alpha = 1;
            self.abTableView.transform = CGAffineTransformIdentity;
        }];
        
        //清空显示数组，加载本地联系人数组
        [self.cyPersonSections removeAllObjects];
        [self.cyPersonSections addObjectsFromArray:self.localAddressBooks];
        
        //隐藏无数据提示文字
        self.hintLabel.hidden = YES;
        self.tipView.hidden = YES;
        self.reloadSXBtn.hidden = YES;
        self.reloadYSBtn.hidden = YES;
        
        [self.abTableView reloadData];
    } else if (s.selectedSegmentIndex == CYIndexThird) {//疑似失信人
        //隐藏搜素框以及失信匹配的联系人
        self.abSearchBar.alpha = 0;
        self.abTableView.transform = CGAffineTransformMakeTranslation(0, self.abSearchBar.frame.size.height +20);
        self.reloadSXBtn.hidden = YES;
        
        //失信匹配人为空时显示无数据提示文字
        if (!self.ysTricksters.count) {
           CYAlertView(@"暂无数据");
            if (self.ysLoadState) {
                self.hintLabel.hidden = NO;
                self.hintLabel.text = self.ysHint;
                if (CYStringEqualTo(self.ysHint, @"网络出错")) {
                    self.reloadYSBtn.hidden = NO;
                    self.reloadSXBtn.hidden = YES;
                } else {
                    self.reloadYSBtn.hidden = YES;
                    self.reloadSXBtn.hidden = YES;
                }
            } else {
                [MBProgressHUD showMessage:@"数据加载中" toView:self.abTableView];
                self.hintLabel.hidden = YES;
            }
        } else {
            self.hintLabel.hidden = YES;
            self.reloadSXBtn.hidden = YES;
            self.reloadYSBtn.hidden = YES;
            [MBProgressHUD hideHUDForView:self.abTableView animated:NO];
            
            //清空显示数组，加载疑似失信人
            [self.cyPersonSections addObjectsFromArray:self.ysTricksters];
        }
        
        [self.view addSubview:self.ysTricksterVC.view];
    }
    [self.abTableView reloadData];
}

/**
 *  设置无数据提示view
 */
- (void)setupHintView {
    UILabel *label = [[UILabel alloc] init];
    label.hidden = YES;
    label.frame = (CGRect){CGPointMake(0, self.view.center.y - 50), CGSizeMake(self.view.frame.size.width, 100)};
    label.text = @"没有更多数据";
    label.font = [UIFont boldSystemFontOfSize:20];
    label.textColor = [UIColor grayColor];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    self.hintLabel = label;
    
    self.reloadYSBtn = [self reloadBtnWithAction:@selector(reloadYS:)];
    self.reloadSXBtn = [self reloadBtnWithAction:@selector(reloadSX:)];
    
}

- (UIButton *)reloadBtnWithAction:(SEL)action {
    UIButton *ysBtn = [[UIButton alloc] init];
    ysBtn.frame = CGRectMake(self.view.center.x - 40, self.view.center.y + 20, 80, 30);
    [ysBtn setTitle:@"刷新" forState:UIControlStateNormal];
    [ysBtn setTitleColor:CYNaviThemeColor forState:UIControlStateNormal];
    ysBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    ysBtn.layer.cornerRadius = 4;
    ysBtn.layer.borderWidth = 1;
    ysBtn.layer.borderColor = CYNaviThemeColor.CGColor;
    ysBtn.backgroundColor = [UIColor clearColor];
    [self.view addSubview:ysBtn];
    [ysBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    ysBtn.hidden = YES;
    
    return ysBtn;
}

- (void)reloadYS:(UIButton *)btn {
    self.reloadSXBtn.hidden = YES;
    self.reloadYSBtn.hidden = YES;
    self.hintLabel.hidden = YES;
    self.tipView.hidden = YES;
    [MBProgressHUD showMessage:@"刷新中" toView:self.abTableView];
    //匹配疑似失信人
    [self loadYsTricksters];
}

- (void)reloadSX:(UIButton *)btn {
    self.reloadSXBtn.hidden = YES;
    self.reloadYSBtn.hidden = YES;
    self.hintLabel.hidden = YES;
    self.tipView.hidden = YES;
    [MBProgressHUD showMessage:@"刷新中" toView:self.abTableView];
    [self loadTricksters];
}

#pragma mark - CYAddressBookCellDelegate iconBtn点击代理
/**
 *  cell右边icon点击
 */
- (void)iconBtnClick:(UIButton *)btn {
//    CYLog(@"iconBtnClick:%ld", (long)btn.tag);
}
/**
 *  iconBtn代理点击
 */
- (void)cell:(CYAddressBookCell *)cell iconButton:(UIButton *)btn {
    if (cell.person.iconType == CYIconTypeYS) {
        CYYSDetailVC *YSDetail = [[CYYSDetailVC alloc] init];
        YSDetail.person = cell.person;
        YSDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:YSDetail animated:YES];
    } else if (cell.person.iconType == CYIconTypeSX) {
//        CYABDetailVController *controll = [[CYABDetailVController alloc] init];
        CYABDetailPageVC *controll = [[CYABDetailPageVC alloc] initWithPerson:cell.person andCallRecord:nil defrId:cell.person.simpleRecord.recordId];
        cell.person.pushTag = 1;
        cell.person.segmentTag = 1;
//        controll.person = cell.person;
        controll.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controll animated:YES];
    }
}

#pragma mark - CYTabBarVControllerDelegate
- (void)tabBar:(XCTabBarView *)tabBar didSelectTo:(NSInteger)to {
    
}

#pragma mark - 监听
- (void)setupNotification {
    //通讯录修改通知
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(addressBookChanged:) name:RHAddressBookExternalChangeNotification object:nil];
}
/**
 *  监听系统通讯录的更改
 *
 *  @param notifi
 */
- (void)addressBookChanged:(NSNotification *)notifi {
    [self reloadAbtableViewDataSource];
    if (self.selectedSegIndex == CYIndexFirst) {
        [self.abTableView reloadData];
    }
}

#pragma mark - 搜索点击代理
- (void)tableView:(CYSearchTVController *)tableView cellDidSelected:(UITableViewCell *)cell {
    [self.abSearchBar resignFirstResponder];//设置不做第一响应者
}

- (void)setExtraCellLineHidden {
    UIView *view =[[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.abTableView setTableFooterView:view];
    [self.searchDisplayController.searchResultsTableView setTableFooterView:view];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([sender isKindOfClass:[UITableViewCell class]]) {
        NSIndexPath *index = [self.abTableView indexPathForCell:sender];
        CYPerson *cyPerson = self.cyPersonSections[index.section][index.row];
        cyPerson.pushTag = 1;
        CYABDetailVController *controller = segue.destinationViewController;
        controller.person = cyPerson;
    }
}

- (void)dealloc {
//    [CYNotificationCenter removeObserver:self name:RHAddressBookExternalChangeNotification object:nil];
    [CYNotificationCenter removeObserver:self];
    CYLog(@"通讯录销毁");
}
@end
